#include "../source/server.hpp"

std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
void ConnectionDestroy(const PtrConnection &conn) {
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection &conn) {
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}

void OnMseeage(const PtrConnection &conn, Buffer *buf) { 
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());
}

void Acceptor(EventLoop *loop, Channel* lst_channel) {
    int fd = lst_channel->Fd();
    int newfd = accept(fd, nullptr, nullptr);
    if(newfd < 0) return;

    PtrConnection conn (new Channel(loop, conn_id, newfd));
    conn->SetMessageCallback(std::bind(OnMseeage, conn, Buffer *buf));//为通信套接字设置可读事件的回调函数
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, conn));
    conn->SetConnectedCallback(std::bind(OnConnected, conn));
    conn->EnableInactiveRelease(10);
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
    conn_id++;
}
int main()
{
    EventLoop loop;
    Socket lst_sock;
    lst_sock.CreatServer(8005);
    //为监听套接字创建一个channel进行事件的管理和处理
    Channel channel(&loop,lst_sock.Fd());
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));//回调中，获取新链接，为新链接创建Channel并添加监控
    channel.EnableRead();//启动可读事件监控
    while(1)
    {
        loop.Start();
        // std::vector<Channel*> actives;
        // poller.Poll(&actives);
        // for(auto &a : actives) {
        //     a->HandleEvent();
        // }
        // int newfd = lst_sock.Accept();
        // if(newfd < 0)
        // {
        //     continue;
        // }
        // Socket cli_sock(newfd);
        // char buf[1024] = {0};
        // int ret = cli_sock.Recv(buf, 1023);
        // if(ret < 0)
        // {
        //     cli_sock.Close();
        //     continue;
        // }
        // cli_sock.Send(buf, ret);
        // cli_sock.Close();
    }
    lst_sock.Close();
    return 0;
}